const WebSocket = require('ws');
const url = require('url');
const clientMap = new Map();

const wss = new WebSocket.Server({ port: 8081 });

wss.on('connection', (ws, req) => {
    const id = url.parse(req.url, true).query.id;
    if (!id) {
        return;
    }
    clientMap.set(id, ws);

    ws.on('message', message => {
        if (isJsonString(message)) {
            const data = JSON.parse(message);
            const { toId, content } = data;
            const toClient = clientMap.get(String(toId));
            if (toClient && toClient.readyState === WebSocket.OPEN) {
                console.log(content);
                toClient.send(content);
            } else {
                console.log("toClient does not exist."); 
            }
        } else {
            const toClient = clientMap.get(String(2));
            if (toClient && toClient.readyState === WebSocket.OPEN) {
                //console.log(message);
                toClient.send(message);
            } else {
                //console.log("toClient2 does not exist."); 
            }         
        }


        /*clients.forEach(client => {
            if (client.readyState === WebSocket.OPEN) {
                console.log(message);
                client.send(message);
            }
        });*/
    });

    ws.on('close', () => {
        // 当连接关闭时，从映射中移除客户端
        for (const [id, conn] of clientMap) {
          if (conn === ws) {
            clientMap.delete(id);
            console.log(`Client ${id} disconnected.`);
            break;
          }
        }
      });
});

function isJsonString(str) {
    try {
      JSON.parse(str);
      return true;
    } catch (e) {
      return false;
    }
  }

console.log('WebSocket server is running on ws://localhost:8081');